<?php
declare (strict_types=1);

namespace app\admin\logic\system;

use app\admin\logic\user\Account;
use app\admin\model\system\Log as LogModel;
use app\common\exception\LogicException;

/**
 * 系统日志
 */
class Log
{

    /**
     * 写入操作日志
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-16
     *
     * @param string $key   [description]
     * @param array  $value [description]
     */
    public static function write(string $content, string $logModule = '', string $logType = 'action', bool $prefixUser = false)
    {
        $log = new LogModel();
        if ($prefixUser) {
            $user         = '管理员【' . request()->user->user_name . '/' . request()->user->id . '】';
            $log->content = $user . $content;
        } else {
            $log->content = $content;
        }

        $log->log_type   = $logType;
        $log->log_module = $logModule;

        if (!$log->save()) {
            throw new LogicException("添加失败");
        }
    }

    /**
     * 日志列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-17
     *
     * @return   [type]                         [description]
     */
    public function getList(array $map = [])
    {
        $model    = new LogModel();
        $pageSize = $model->getListRows();

        // 按用户查找
        if (isset($map['phone'])) {
            $admin_user_id = (int)app(Account::class)->withTrashed()->where('phone', $map['phone'])->value('id');
            $model         = $model->where('admin_user_id', $admin_user_id);
        }

        // 按时间
        if (isset($map['create_time'])) {
            $model = $model->withSearch(['create_time'], ['create_time' => $map['create_time']]);
        }

        return $model->with(['user'])->order('create_time', 'DESC')->paginate($pageSize)->bindAttr('user', ['user_name', 'phone'])->append(['log_type_text']);
    }
}
